#include "grpcclientproxyinserver.h"
#include "grpceventserverservice.h"


GrpcClientProxyInService::GrpcClientProxyInService(std::string name, GrpcEventServerService* parent)
    :m_name(name)
    ,m_parent(parent)
    ,m_canWrite(true)
{
}

void GrpcClientProxyInService::SendEvent(const std::string &jsonText)
{
    {
        GrpcEventMessage message;
        message.set_jsontext(jsonText);

        std::lock_guard<std::mutex> lk(m_mutex);
        m_dataQueue.push(message); //注意不能使用emplace 哦
    }
    WriteOneData();
}

void GrpcClientProxyInService::OnDone()
{
    //只有调用了Finish 才会执行该干啥，
    //而m_canWrite 是没有置位的，所有执行该函数时不会执行新的写操作，安全

    m_parent->ClientEndFlow(m_name);
    delete this; //删除自己
}

void GrpcClientProxyInService::OnWriteDone(bool ok)
{
    if(ok)
    {
        //处理发送完的数据
        {
            std::lock_guard<std::mutex> lk(m_mutex);
            if(!m_dataQueue.empty())
                m_dataQueue.pop();
            //可以继续发送
            m_canWrite = true;
        }

        WriteOneData();
    }
    else
    {
        Finish(Status::CANCELLED);
    }

}

void GrpcClientProxyInService::WriteOneData()
{
    std::lock_guard<std::mutex> lk(m_mutex);
    if(m_canWrite && !m_dataQueue.empty())
    {
        //写一次数据，未完成不能写新数据
        m_canWrite = false;
        StartWrite(&m_dataQueue.front());
    }
}
